<?php
class AddressModel extends Model {

    public function __construct() {
        parent::__construct();
        $this->fields = array('id','name','user','address','email','phone','building','zipcode','selected','province');
        $this->tables = array(DB_FREFIX.'address');
        $this->check = new AddressCheck();
        list(
            $this->R['id'],
            $this->R['user'],
        ) = $this->getRequest()->getParams(array(
            isset($_GET['id']) ? $_GET['id'] : null,
            isset($_COOKIE['user']) ? $_COOKIE['user'] : null
            )
        );
    }

    public function findOne() {
        return parent::select($this->tables,$this->fields,array('where'=>array('user='.$this->R['user'].' AND selected=1')));
    }

    public function findAll() {
        return parent::select($this->tables,$this->fields,array('where'=>array('user='.$this->R['user']),'order'=>'selected DESC'));
    }

    public function add() {
        $condition = array('user='.$this->R['user']);
        $updateData['selected'] = 0;
        parent::update($updateData,$condition);
        $needData = $this->getRequest()->filter($this->fields);
        if(!$this->check->addCheck($this)) $this->check->displayError();
        $needData['user'] = $_COOKIE['user'];
        $needData['selected'] = 1;
        $needData['province'] = $_POST['province'];
        $needData['address'] = $_POST['province'].$_POST['city'].$_POST['area'].$_POST['address'];
        return parent::add($needData);
    }

    public function selected() {
        //先把所有和当前用户有关的收货人地址取消首先，然后再把选中的收货人地址首选
        $condition = array('user='.$this->R['user']);
        $updateData['selected'] = 0;
        parent::update($updateData,$condition);
        $condition = array('id='.$this->R['id']);
        $updateData['selected'] = 1;
        return parent::update($updateData,$condition);
    }

    public function deleteAddress() {
        $condition = array('id='.$this->R['id']);
        if(!$this->check->oneCheck($this,$condition)) $this->check->displayError();
        return parent::delete($condition);
    }

}


?>